package mahan.test.data.mongodb;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.List;

import mahan.data.model.Images;
import mahan.data.mongodb.MahanDB;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

public class ImagesTestCase {
	private MahanDB mahanDb;

	@After
	public void clean() {
		mahanDb.get().dropDatabase();
	}

	@Before
	public void setup() {
		mahanDb = new MahanDB("localhost", 27017, "imagesdb");
		DB db = mahanDb.get();
		assertNotNull(db);
	}

	@SuppressWarnings({ "unchecked" })
	@Test
	public void testImages() throws Exception {
		String[] large = new String[] { "a.gif", "b.gif", "c.gif" };
		String[] thumb = new String[] { "a1.gif", "b1.gif", "c1.gif" };

		clean();
		Images images = new Images(1);
		images.setLargeImages(Arrays.asList(large));
		images.setThumbnails(Arrays.asList(thumb));

		// Store into DB
		BasicDBObject dbo = new BasicDBObject();
		dbo.putAll(images.get());
		DBCollection coll = mahanDb.createCollection("images");
		coll.save(dbo);

		// Retrieve from DB
		DBObject fromDB = coll.findOne();
		Images from = Images.instance();
		from.put(fromDB.toMap());

		assertEquals(1, from.getProductID());
		List<String> retrievedLarge = from.getLargeImages();
		List<String> retrievedThumb = from.getThumbnails();

		assertEquals(3, retrievedLarge.size());
		assertTrue(retrievedLarge.contains("a.gif"));
		assertTrue(retrievedLarge.contains("b.gif"));
		assertTrue(retrievedLarge.contains("c.gif"));

		assertEquals(3, retrievedThumb.size());
		assertTrue(retrievedThumb.contains("a1.gif"));
		assertTrue(retrievedThumb.contains("b1.gif"));
		assertTrue(retrievedThumb.contains("c1.gif"));
	}
}